import { Injectable, ModuleWithProviders, NgModule } from '@angular/core';
import { getActionTypeFromInstance, NGXS_PLUGINS, NgxsNextPluginFn, NgxsPlugin } from '@ngxs/store';
import { SystemAction } from '../system';
import Logout = SystemAction.Logout;

@Injectable()
export class LogoutPlugin implements NgxsPlugin {
  constructor() {
  }

  handle(state: any, action: any, next: NgxsNextPluginFn): any {
    if (getActionTypeFromInstance(action) === Logout.type) {
      state = {};
    }
    return next(state, action);
  }
}

@NgModule()
export class NgxsLogoutPluginModule {
  static forRoot(): ModuleWithProviders<NgxsLogoutPluginModule> {
    return {
      ngModule: NgxsLogoutPluginModule,
      providers: [
        {
          provide: NGXS_PLUGINS,
          useClass: LogoutPlugin,
          multi: true,
        },
      ],
    };
  }
}
